package User.FunctionPkg;

import MySQL_im.getInfo;
import User.UserWin;
import Warning.ShowUI;
import Warning.WarnDialog;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Arrays;
import java.util.Vector;

public class Research extends JFrame implements Win, MouseListener, ActionListener {
    String[] TiZhi = {"阳虚质","阴虚质","气虚质","痰湿质","湿热质","血瘀质","气郁质","特禀质","平和质"};
    boolean once=true;
    boolean once_1=true;
    getInfo info = new getInfo();
    ShowUI showUI;
    ImageIcon bk_img = new ImageIcon("images/答卷背景.jpg");
    JFrame panel = new JFrame();
    WarnDialog ans;
    WarnDialog handout;
    String user;
    ImageIcon next_img = new ImageIcon("images/下一页.png");
    ImageIcon last_img = new ImageIcon("images/上一页.png");
    JLabel bk = new JLabel(bk_img);
    Connection con = new getInfo().getConnection();
    Statement st =null;
    int currentPage =1;
    int[][] num = {{0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0},{0,0,0,0,0,0,0},{0,0,0,0,0,0,0},{0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}};
    int[] sum = new int[9];
    JLabel title;
    JPanel pan;
    JLabel tips = new JLabel("<html>选项从前到后依次对应：没有（根本不）、很少（有一点）、有时（有些）、经常（相当）、总是（非常）</html>");
    int len=110;
    String q;
    ButtonGroup[] choose;
    JRadioButton[][] scores;
    JLabel[] questions;
    Box[] searchBox;
    JButton certain = new JButton("提交");
    JButton out = new JButton("退出");
    JButton next = new JButton("下一页",next_img);
    UserWin user_win;
    //        界面初始化
    public Research(String name,UserWin jPanel) {
        once = true;
        once_1=true;
        user_win = jPanel;
        user = name;
        q = "SELECT * FROM q0"+currentPage;
        ResultSet re = null;
        try {
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
            re = st.executeQuery(q);
            re.last();
            int max = re.getRow();
            scores = new JRadioButton[max][5];
            questions = new JLabel[max];
            searchBox = new Box[max];
            choose = new ButtonGroup[max];
//            System.out.println(max);
            for (int i = 0; i < max; i++) {
                re.absolute(i);
                re.next();
                searchBox[i] = Box.createVerticalBox();
                questions[i] = new JLabel("<html>"+re.getString(1)+"</html>");
                questions[i].setFont(new Font("楷体",Font.PLAIN,20));
                searchBox[i].add(questions[i]);
                choose[i]=new ButtonGroup();
//                System.out.println(questions[i]);
                for (int j = 0; j < 5; j++) {
                    scores[i][j]=new JRadioButton(re.getString(j+2));
                    choose[i].add(scores[i][j]);
                }
//                searchBox[i].add(ansBox[i]);
                searchBox[i].setBounds(17,len,700,30);
                for (int j = 0; j < 5; j++) {
                   scores[i][j].setBounds(50+j*50,len+32,50,30);
                   scores[i][j].addActionListener(this);
                }
                len += 70;
            }
            next.setVerticalTextPosition(SwingConstants.BOTTOM);
            next.setFont(new Font("黑体",Font.BOLD,12));
            next.setHorizontalTextPosition(SwingConstants.CENTER);
            out.addMouseListener(this);
            certain.addMouseListener(this);
        } catch (SQLException e) {
            System.out.println(e);
        }
        title = new JLabel("中医体质测试"+currentPage,SwingConstants.CENTER);
        init();
    }
    //        界面第一次布局
    public void init(){
        panel.setBounds(558,138,735,750);
        panel.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        bk.setSize(bk_img.getIconWidth(),bk_img.getIconHeight());
        panel.getLayeredPane().add(bk,new Integer(Integer.MIN_VALUE));
        pan = (JPanel)panel.getContentPane();
        pan.setOpaque(false);
        pan.setLayout(null);
        pan.add(title);
        title.setFont(new Font("华文行楷",Font.BOLD,30));
        title.setBounds(0,0,735,50);
        pan.add(tips);
        tips.setFont(new Font("黑体",Font.BOLD,20));
        tips.setBounds(22,55,690,50);
        for (int i = 0; i < questions.length; i++) {
            pan.add(searchBox[i]);
            for (int j = 0; j < 5; j++) {
                pan.add(scores[i][j]);
                scores[i][j].setOpaque(false);
            }
        }
        next.setBounds(500,0,60,60);
        next.addActionListener(this);
        pan.add(out);
        if(currentPage==9){
            pan.add(certain);
            certain.setBounds(200,len,100,30);
            out.setBounds(400,len,100,30);
        }
        else{
            if(currentPage==1){
                pan.add(next);
            }
            else{
                pan.add(next);
            }
            out.setBounds(300,len,100,30);
        }
        panel.setTitle("数据调查");
        panel.setVisible(true);
        validate();
        ans = new WarnDialog("注意","现在退出的话答卷进度将会清零，您确定退出吗？",panel);
        handout = new WarnDialog("提醒","是否确认提交？",panel);
    }
//    界面更新
    public void actionPerformed(ActionEvent e){
        Object obj = e.getSource();
        if(obj==next){
            if(HaveNZero(currentPage)){
                sum[currentPage-1]=(int)((double) (Arrays.stream(num[currentPage-1]).sum()-num[currentPage-1].length)/(num[currentPage-1].length*4)*100);
                AddInfo(currentPage);
                currentPage += 1;
                UpdatePage();
            }
            else{
                showUI = new ShowUI("警告","请先完成所有题目，再进入下一页");
            }
        }
        for (int i = 0; i < questions.length; i++) {
            for (int j = 0; j < 5; j++) {
                if(scores[i][j]==obj){
                    num[currentPage-1][i]=Integer.parseInt(scores[i][j].getText());
                    System.out.println(Arrays.toString(num[currentPage - 1]));
                }
            }
        }
    }
//    弹出退出界面，仅弹出一次，便不再弹出
    public void mouseClicked(MouseEvent e){
        Object obj = e.getSource();
        if(obj == out){
            if (once){
                ans.Start();
                once = ans.Ans();
            }
        }
        if(obj==certain){
            if(once_1){
                if(HaveNZero(currentPage)){
                    sum[currentPage-1]=(int)((double) (Arrays.stream(num[currentPage-1]).sum()-num[currentPage-1].length)/(num[currentPage-1].length*4)*100);
                    AddInfo(currentPage);
                    info.UpdateType(user,Result());
                    UpdateSQL();
                    user_win.UpdateInfo();
                    handout.Start();
                    once_1 = handout.Ans();
                }
                else{
                    showUI = new ShowUI("警告","请先完成所有题目，才能提交");
                }
            }
        }
    }
    public void mousePressed(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
//    更新上下翻页
    public void UpdatePage(){
        once = true;
        pan.removeAll();
        len=110;
        title = new JLabel("中医体质测试"+currentPage,SwingConstants.CENTER);
        q = "SELECT * FROM q0"+currentPage;
        ResultSet re = null;
//        更新源数据
        try {
            re = st.executeQuery(q);
            re.last();
            int max = re.getRow();
            scores = new JRadioButton[max][5];
            questions = new JLabel[max];
            searchBox = new Box[max];
            choose = new ButtonGroup[max];
            for (int i = 0; i < max; i++) {
                re.absolute(i);
                re.next();
                searchBox[i] = Box.createVerticalBox();
                questions[i] = new JLabel("<html>"+re.getString(1)+"</html>");
                questions[i].setFont(new Font("楷体",Font.PLAIN,20));
                searchBox[i].add(questions[i]);
                choose[i]=new ButtonGroup();
                for (int j = 0; j < 5; j++) {
                    scores[i][j]=new JRadioButton(re.getString(j+2));
                    choose[i].add(scores[i][j]);
                }
                searchBox[i].setBounds(17,len,700,30);
                for (int j = 0; j < 5; j++) {
                    scores[i][j].setBounds(50+j*50,len+32,50,30);
                    scores[i][j].addActionListener(this);
                }
                len += 70;
            }
            next.setVerticalTextPosition(SwingConstants.BOTTOM);
            next.setFont(new Font("黑体",Font.BOLD,12));
            next.setHorizontalTextPosition(SwingConstants.CENTER);
            out.addMouseListener(this);
            certain.addMouseListener(this);
        } catch (SQLException ex) {
            System.out.println(ex.toString());
        }
        pan.repaint();
        pan.add(title);
        title.setFont(new Font("华文行楷",Font.BOLD,30));
        title.setBounds(0,0,735,50);
        pan.add(tips);
        for (int i = 0; i < questions.length; i++) {
            pan.add(searchBox[i]);
            for (int j = 0; j < 5; j++) {
                pan.add(scores[i][j]);
                scores[i][j].setOpaque(false);
            }
        }
        pan.add(out);
        if(currentPage==9){
            pan.add(certain);
            certain.setBounds(200,len,100,30);
            out.setBounds(400,len,100,30);
        }
        else{
            if(currentPage==1){
                pan.add(next);
            }
            else{
                pan.add(next);
            }
            out.setBounds(300,len,100,30);
        }
        pan.updateUI();
    }
    boolean HaveNZero(int currentPage){
        boolean has=true;
        for (int i = 0; i < num[currentPage-1].length; i++) {
            if(num[currentPage-1][i]==0){
                has=false;
                break;
            }
        }
        return has;
    }
    public void AddInfo(int currentPage){
        String type = null;
        if(currentPage==1){
            type="YangXu";
        }
        if(currentPage==2){
            type="YinXu";
        }
        if(currentPage==3){
            type="QiXu";
        }
        if(currentPage==4){
            type="TanShi";
        }
        if(currentPage==5){
            type="ShiRe";
        }
        if(currentPage==6){
            type="XieYu";
        }
        if(currentPage==7){
            type="QiYu";
        }
        if(currentPage==8){
            type="TeBin";
        }
        if(currentPage==9){
            type="PingHe";
        }
        info.UpdateData(user,sum[currentPage-1],type);
    }
//    返回判定结果
    public String Result(){
        int PingHe = sum[sum.length-1];
        int count_30=0;
        int count_40=0;
        int countLT40=0;
//        倾向数量
        Vector<String>QingXiang = new Vector<>();
//        偏颇
        Vector<String>PP = new Vector<>();
        String ans = null;
//        判断各个分数段满足条件的数量
        for (int i = 0; i < sum.length-1; i++) {
            if(sum[i]<40)
                count_40++;
            if(sum[i]<30)
                count_30++;
            if(sum[i]<=39 && sum[i]>=30){
                QingXiang.add(TiZhi[i]);
            }
            if(sum[i]>=40){
                countLT40++;
                PP.add(TiZhi[i]);
            }
        }
//        满足平和质的分数情况下
        if(PingHe>=60){
            if(count_30== sum.length-1)
                ans="您的体质可判定为平和质。";
            else if(count_40== sum.length-1){
                if(QingXiang.isEmpty())
                    ans="您的体质基本是平和质，暂无其他体质的明显倾向。";
                else{
                    String QX = String.join("、",QingXiang);
                    ans="您的体质基本是平和质，但有"+QX+"的倾向。";
                }
            }
            else{
                if(countLT40==1){
                    if(QingXiang.isEmpty()){
                        ans="您的体质是"+PP.firstElement()+"暂无其他体质的明显倾向。";
                    }
                    else{
                        String QX = String.join("、",QingXiang);
                        ans="您的体质是"+PP.firstElement()+"同时，有"+QX+"的倾向";
                    }
                }
                if(countLT40>1){
                    String Pp = String.join("、",PP);
                    if(QingXiang.isEmpty()){
                        ans="您的体质是"+Pp+"的兼夹体质，暂无其他体质的明显倾向。";
                    }
                    else{
                        String QX = String.join("、",QingXiang);
                        ans="您的体质是"+Pp+"的兼夹体质，同时，有"+QX+"的倾向";
                    }
                }
            }
        }
//        不满足平和质分数的情况下
        else{
            if(countLT40==1){
                if(QingXiang.isEmpty()){
                    ans="您的体质是"+PP.firstElement()+"暂无其他体质的明显倾向。";
                }
                else{
                    String QX = String.join("、",QingXiang);
                    ans="您的体质是"+PP.firstElement()+"同时，有"+QX+"的倾向";
                }
            }
            if(countLT40>1){
                String Pp = String.join("、",PP);
                if(QingXiang.isEmpty()){
                    ans="您的体质是"+Pp+"的兼夹体质，暂无其他体质的明显倾向。";
                }
                else{
                    String QX = String.join("、",QingXiang);
                    ans="您的体质是"+Pp+"的兼夹体质，同时，有"+QX+"的倾向";
                }
            }
            if(count_40== sum.length-1){
                String QX = String.join("、",QingXiang);
                ans="您的体质是"+QX+"的兼夹体质";
            }
        }
        return ans;
    }
    public void UpdateSQL(){
        Date dateTime = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = dateFormat.format(dateTime);
        String url = "insert into "+user+"_user values('"+formattedDate+"','"+Result()+"',"+sum[sum.length-1]+","+sum[2]+","+sum[0]+","+sum[1]+","+sum[3]+","+sum[4]+","+sum[5]+","+sum[6]+","+sum[7]+")";
        try {
            st.executeUpdate(url);
            st.close();
            con.close();
        } catch (SQLException e) {
            System.out.println(e.toString());
        }
    }
}